const { ipcRenderer, path, fs, selectedFileName, rootPath, getMatchingFolderPath } = require('../scripts/common.js');

// 添加模式跟踪变量
let isAbilityDetailMode = false;
let isMaterialDetailMode = false;
let isMethodDetailMode = false;

// 属性相关功能
document.getElementById('propertiesLabel').onclick = async () => {
    const fileContent = document.getElementById('fileContent');
    
    // 检查第三区域是否为空
    if (fileContent.innerHTML.trim() !== '') {
        // 如果第三区域不为空，清空第三区域、第四区域和下方配方区
        fileContent.innerHTML = '';
        document.querySelector('.card-4').innerHTML = '';
        document.querySelector('.pink-card').innerHTML = '';
    } else {
        // 如果第三区域为空，只清空下方配方区
        document.querySelector('.pink-card').innerHTML = '';
    }

    const fileList = document.getElementById('fileList');
    try {
        const matchingFolderPath = getMatchingFolderPath();
        if (matchingFolderPath) {
            const skillpointPath = path.join(matchingFolderPath, 'skillpoint.json');
            if (fs.existsSync(skillpointPath)) {
                const content = fs.readFileSync(skillpointPath, 'utf8');
                displaySkillpointContent(content, skillpointPath);
            } else {
                throw new Error('skillpoint.json not found');
            }
        } else {
            throw new Error('Matching folder not found');
        }
    } catch (error) {
        console.error('Error:', error);
        fileList.innerHTML = '读取skillpoint.json失败：' + error.message;
    }
};

function displaySkillpointContent(content, filePath) {
    const fileList = document.getElementById('fileList');
    fileList.innerHTML = '';

    // 添加"+"按钮
    const addButton = document.createElement('div');
    addButton.className = 'file-item add-button';
    addButton.textContent = '+';
    addButton.onclick = () => {
        // 在第三个区域显示选择界面
        const fileContent = document.getElementById('fileContent');
        try {
            const componentHtml = loadComponent('properties');
            if (!componentHtml || componentHtml.includes('失败') || componentHtml.includes('不存在')) {
                throw new Error('无法加载属性选择界面');
            }
            
            fileContent.innerHTML = componentHtml;
            
            // 绑定类型选择按钮事件
            fileContent.querySelectorAll('.attribute-type-button').forEach(button => {
                button.onclick = () => {
                    const type = button.dataset.type;
                    showAttributeForm(type, filePath);
                };
            });

            // 绑定返回按钮事件
            const returnButton = fileContent.querySelector('.return-button');
            if (returnButton) {
                returnButton.onclick = () => {
                    fileContent.innerHTML = '';
                    const content = fs.readFileSync(filePath, 'utf8');
                    displaySkillpointContent(content, filePath);
                };
            }
        } catch (error) {
            console.error('Error loading properties component:', error);
            fileContent.innerHTML = '加载属性选择界面失败: ' + error.message;
        }
    };
    fileList.appendChild(addButton);

    // 显示现有属性
    const data = JSON.parse(content);
    createAttributeSection('能力点', data.attributes.filter(attr => attr.type === 'ability'));
    createAttributeSection('原材料', data.attributes.filter(attr => attr.type === 'material'));
    createAttributeSection('方法库', data.attributes.filter(attr => attr.type === 'method'));
}

function createAttributeSection(title, attributes) {
    const section = document.createElement('div');
    section.className = 'attribute-section';
    
    const titleDiv = document.createElement('div');
    titleDiv.className = 'attribute-section-title';
    titleDiv.textContent = title;
    section.appendChild(titleDiv);
    
    attributes.forEach(attr => {
        const div = document.createElement('div');
        div.className = 'file-item';
        div.textContent = attr.name;
        div.onclick = () => showAttributeDetail(attr);
        section.appendChild(div);
    });
    
    document.getElementById('fileList').appendChild(section);
}

function showAttributeTypeSelection(filePath) {
    // 在第三个区域（fileContent）显示选择界面
    const fileContent = document.getElementById('fileContent');
    fileContent.innerHTML = loadComponent('properties');

    // 绑定类型选择按钮事件
    const buttons = fileContent.querySelectorAll('.attribute-type-button');
    buttons.forEach(button => {
        button.onclick = () => {
            const type = button.dataset.type;
            showAttributeForm(type, filePath);
        };
    });

    // 绑定返回按钮事件
    const returnButton = fileContent.querySelector('.return-button');
    if (returnButton) {
        returnButton.onclick = () => {
            const content = fs.readFileSync(filePath, 'utf8');
            displaySkillpointContent(content, filePath);
            fileContent.innerHTML = ''; // 清空选择界面
        };
    }
}

function showAttributeForm(type, filePath) {
    const fileContent = document.getElementById('fileContent');
    fileContent.innerHTML = `
        <div class="attribute-form">
            <div class="form-group">
                <label>属性名称*</label>
                <input type="text" id="attrName" placeholder="请输入属性名称">
            </div>
            <div class="form-group">
                <label>变量名*</label>
                <input type="text" id="attrVarName" placeholder="请输入英文变量名">
            </div>
            <div id="attributeTypeFields">
                ${getTypeSpecificFields(type)}
            </div>
            <div class="button-group">
                <button class="return-btn" onclick="document.getElementById('propertiesLabel').click()">返回</button>
                <button class="save-btn" id="saveAttr" disabled>保存</button>
            </div>
        </div>
    `;

    // 绑定保存按钮事件
    const saveButton = document.getElementById('saveAttr');
    if (saveButton) {
        saveButton.onclick = () => saveAttribute(type, filePath);
    }

    // 绑定输入验证
    const nameInput = document.getElementById('attrName');
    const varNameInput = document.getElementById('attrVarName');
    if (nameInput && varNameInput && saveButton) {
        const validateInputs = () => {
            saveButton.disabled = !nameInput.value.trim() || !varNameInput.value.trim();
        };
        nameInput.oninput = validateInputs;
        varNameInput.oninput = validateInputs;
    }
}

// 获取不同类型的特定字段
function getTypeSpecificFields(type) {
    switch (type) {
        case 'ability':
            return `
                <div class="form-group">
                    <label>初始值</label>
                    <input type="number" id="attrDefaultValue" placeholder="默认值">
                </div>
                <div class="form-group">
                    <label>上限</label>
                    <input type="number" id="attrMax" placeholder="最大值">
                </div>
                <div class="form-group">
                    <label>详情</label>
                    <textarea id="attrDetail" placeholder="属性详情"></textarea>
                </div>
                <div class="form-group">
                    <label>增加途径</label>
                    <textarea id="attrIncrease" placeholder="增加能力点的途径"></textarea>
                </div>
                <div class="form-group">
                    <label>降低途径</label>
                    <textarea id="attrDecrease" placeholder="降低能力点的途径"></textarea>
                </div>
            `;

        case 'material':
            return `
                <div class="form-group">
                    <label>单位</label>
                    <input type="text" id="attrUnit" placeholder="个、杯、篇">
                </div>
                <div class="form-group">
                    <label>步长</label>
                    <input type="number" id="attrStep" placeholder="如：0.5、1、10">
                </div>
                <div class="form-group">
                    <label>详情</label>
                    <textarea id="attrDetail" placeholder="原材料详情"></textarea>
                </div>
                <div class="form-group">
                    <label>获取途径</label>
                    <textarea id="attrIncrease" placeholder="获取原材料的途径"></textarea>
                </div>
                <div class="form-group">
                    <label>消耗途径</label>
                    <textarea id="attrDecrease" placeholder="消耗原材料的途径"></textarea>
                </div>
            `;

        case 'method':
            return `
                <div class="form-group">
                    <label>详情</label>
                    <textarea id="attrDetail" placeholder="方法详情"></textarea>
                </div>
                <div class="form-group">
                    <label>原理</label>
                    <textarea id="attrPrinciple" placeholder="方法原理"></textarea>
                </div>
                <div class="form-group">
                    <label>来源</label>
                    <textarea id="attrSource" placeholder="方法来源"></textarea>
                </div>
                <div class="form-group">
                    <label>适用范围</label>
                    <textarea id="attrScope" placeholder="适用范围"></textarea>
                </div>
                <div class="form-group">
                    <label>增幅方式列表</label>
                    <div id="amplificationList" class="method-list"></div>
                    <button type="button" class="add-btn" onclick="addAmplification()">添加增幅方式</button>
                </div>
                <div class="form-group">
                    <label>注意事项列表</label>
                    <div id="cautionList" class="method-list"></div>
                    <button type="button" class="add-btn" onclick="addCaution()">添加注意事项</button>
                </div>
            `;
    }
}

function saveAttribute(type, filePath) {
    const attribute = {
        type: type,
        name: document.getElementById('attrName').value.trim(),
        varName: document.getElementById('attrVarName').value.trim()
    };

    // 根据类型添加不同的属性
    switch (type) {
        case 'ability':
            attribute.defaultValue = document.getElementById('attrDefaultValue').value || 0;
            attribute.currentValue = document.getElementById('attrDefaultValue').value || 0;
            attribute.max = document.getElementById('attrMax').value || null;
            attribute.min = 0;
            attribute.step = 1;
            attribute.detail = document.getElementById('attrDetail').value || null;
            attribute.increase = document.getElementById('attrIncrease').value || null;
            attribute.decrease = document.getElementById('attrDecrease').value || null;
            break;

        case 'material':
            attribute.defaultValue = 0;
            attribute.currentValue = 0;
            attribute.min = 0;
            attribute.unit = document.getElementById('attrUnit').value || null;
            attribute.step = document.getElementById('attrStep').value || null;
            attribute.detail = document.getElementById('attrDetail').value || null;
            attribute.increase = document.getElementById('attrIncrease').value || null;
            attribute.decrease = document.getElementById('attrDecrease').value || null;
            break;

        case 'method':
            attribute.detail = document.getElementById('attrDetail').value || null;
            attribute.principle = document.getElementById('attrPrinciple').value || null;
            attribute.source = document.getElementById('attrSource').value || null;
            attribute.scope = document.getElementById('attrScope').value || null;
            attribute.amplification = getListItems('amplification');
            attribute.notes = getListItems('caution');
            break;
    }

    ipcRenderer.invoke('save-attribute', { filePath, attribute })
        .then(result => {
            if (result.success) {
                // 清空第三区域
                document.getElementById('fileContent').innerHTML = '';
                // 更新显示
                displaySkillpointContent(fs.readFileSync(filePath, 'utf8'), filePath);
            } else {
                console.error('Error saving attribute:', result.error);
                alert('保存失败: ' + result.error);
            }
        })
        .catch(error => {
            console.error('Error in save operation:', error);
            alert('保存操作失败: ' + error.message);
        });
}

function getListItems(type) {
    const items = document.getElementById(`${type}List`).getElementsByTagName('input');
    return Array.from(items).map(item => item.value).filter(value => value.trim() !== '');
}

function addListItem(type) {
    const container = document.getElementById(`${type}List`);
    const div = document.createElement('div');
    div.className = 'list-item';
    div.innerHTML = `
        <input type="text" placeholder="请输入内容">
        <button onclick="this.parentElement.remove()">删除</button>
    `;
    container.appendChild(div);
}

function showAttributeDetail(attribute) {
    // 只更新第三区域，不影响其他区域
    const fileContent = document.getElementById('fileContent');
    let html = '<div class="formatted-json">';
    
    // 添加类型显示
    const typeMap = {
        'ability': '能力点',
        'material': '原材料',
        'method': '方法库'
    };
    
    html += `<div class="json-item"><span class="json-key">类型：</span><span class="json-value">${typeMap[attribute.type]}</span></div>`;
    
    // 添加名称和变量名
    html += `<div class="json-item">
        <span class="json-key">名称：</span><span class="json-value">${attribute.name}</span><br>
        <span class="var-name">${attribute.varName}</span>
    </div>`;

    // 根据类型显示不同的内容
    switch (attribute.type) {
        case 'ability':
            // 显示当前值
            html += `<div class="json-item"><span class="json-key">当前值：</span><span class="json-value">${attribute.currentValue || 0}</span></div>`;
            
            // 显示范围
            let rangeText;
            if (attribute.max && attribute.min !== undefined) {
                rangeText = `${attribute.min}-${attribute.max}`;
            } else if (attribute.max) {
                rangeText = `${attribute.max}以下`;
            } else if (attribute.min !== undefined) {
                rangeText = `${attribute.min}以上`;
            } else {
                rangeText = '不限';
            }
            html += `<div class="json-item"><span class="json-key">范围：</span><span class="json-value">${rangeText}</span></div>`;
            
            // 显示其他信息
            html += `<div class="json-item"><span class="json-key">详情：</span><span class="json-value">${attribute.detail || '暂无'}</span></div>`;
            html += `<div class="json-item"><span class="json-key">增长途径：</span><span class="json-value">${attribute.increase || '未知'}</span></div>`;
            html += `<div class="json-item"><span class="json-key">减少途径：</span><span class="json-value">${attribute.decrease || '未知'}</span></div>`;
            break;

        case 'material':
            html += `<div class="json-item"><span class="json-key">当前值：</span><span class="json-value">${attribute.currentValue || 0}${attribute.unit || ''}</span></div>`;
            
            // 显示范围
            let materialRangeText;
            if (attribute.max && attribute.min !== undefined) {
                materialRangeText = `${attribute.min}-${attribute.max}${attribute.unit || ''}`;
            } else if (attribute.max) {
                materialRangeText = `${attribute.max}${attribute.unit || ''}以下`;
            } else if (attribute.min !== undefined) {
                materialRangeText = `${attribute.min}${attribute.unit || ''}以上`;
            } else {
                materialRangeText = '不限';
            }
            html += `<div class="json-item"><span class="json-key">范围：</span><span class="json-value">${materialRangeText}</span></div>`;
            
            html += `<div class="json-item"><span class="json-key">详情：</span><span class="json-value">${attribute.detail || '暂无'}</span></div>`;
            html += `<div class="json-item"><span class="json-key">获取途径：</span><span class="json-value">${attribute.increase || '未知'}</span></div>`;
            html += `<div class="json-item"><span class="json-key">消耗途径：</span><span class="json-value">${attribute.decrease || '未知'}</span></div>`;
            break;

        case 'method':
            html += `<div class="json-item"><span class="json-key">详情：</span><span class="json-value">${attribute.detail || '暂无'}</span></div>`;
            html += `<div class="json-item"><span class="json-key">原理：</span><span class="json-value">${attribute.principle || '未知'}</span></div>`;
            html += `<div class="json-item"><span class="json-key">来源：</span><span class="json-value">${attribute.source || '未知'}</span></div>`;
            html += `<div class="json-item"><span class="json-key">适用范围：</span><span class="json-value">${attribute.scope || '尚不清楚'}</span></div>`;
            
            // 显示增幅方式
            if (attribute.amplification && attribute.amplification.length > 0) {
                html += `<div class="json-item"><span class="json-key">增幅方式：</span><ul class="json-list">`;
                attribute.amplification.forEach(item => {
                    html += `<li>${item}</li>`;
                });
                html += '</ul></div>';
            } else {
                html += `<div class="json-item"><span class="json-key">增幅方式：</span><span class="json-value">尚不清楚</span></div>`;
            }
            
            // 显示注意事项
            if (attribute.notes && attribute.notes.length > 0) {
                html += `<div class="json-item"><span class="json-key">注意事项：</span><ul class="json-list">`;
                attribute.notes.forEach(item => {
                    html += `<li>${item}</li>`;
                });
                html += '</ul></div>';
            } else {
                html += `<div class="json-item"><span class="json-key">注意事项：</span><span class="json-value">尚不清楚</span></div>`;
            }
            break;
    }
    
    html += '</div>';
    fileContent.innerHTML = html;
}

// 修改标签点击事件
document.getElementById('abilityLabel').onclick = () => {
    filterAndDisplayAttributes('ability');
    // 显示对应的模式切换标签，隐藏其他的
    document.getElementById('abilityModeSwitch').style.display = 'block';
    document.getElementById('materialModeSwitch').style.display = 'none';
    document.getElementById('methodModeSwitch').style.display = 'none';
};

document.getElementById('materialLabel').onclick = () => {
    filterAndDisplayAttributes('material');
    // 显示对应的模式切换标签，隐藏其他的
    document.getElementById('abilityModeSwitch').style.display = 'none';
    document.getElementById('materialModeSwitch').style.display = 'block';
    document.getElementById('methodModeSwitch').style.display = 'none';
};

document.getElementById('methodLabel').onclick = () => {
    filterAndDisplayAttributes('method');
    // 显示对应的模式切换标签，隐藏其他的
    document.getElementById('abilityModeSwitch').style.display = 'none';
    document.getElementById('materialModeSwitch').style.display = 'none';
    document.getElementById('methodModeSwitch').style.display = 'block';
};

// 添加模式切换事件
document.getElementById('abilityModeSwitch').onclick = () => {
    isAbilityDetailMode = !isAbilityDetailMode;
    const modeSwitch = document.getElementById('abilityModeSwitch');
    modeSwitch.textContent = isAbilityDetailMode ? '简洁' : '完整';
    filterAndDisplayAttributes('ability');
};

document.getElementById('materialModeSwitch').onclick = () => {
    isMaterialDetailMode = !isMaterialDetailMode;
    const modeSwitch = document.getElementById('materialModeSwitch');
    modeSwitch.textContent = isMaterialDetailMode ? '简洁' : '完整';
    filterAndDisplayAttributes('material');
};

document.getElementById('methodModeSwitch').onclick = () => {
    isMethodDetailMode = !isMethodDetailMode;
    const modeSwitch = document.getElementById('methodModeSwitch');
    modeSwitch.textContent = isMethodDetailMode ? '简洁' : '完整';
    filterAndDisplayAttributes('method');
};

// 修改筛选和显示函数
function filterAndDisplayAttributes(type) {
    try {
        const matchingFolderPath = getMatchingFolderPath();
        if (matchingFolderPath) {
            const skillpointPath = path.join(matchingFolderPath, 'skillpoint.json');
            if (fs.existsSync(skillpointPath)) {
                const content = fs.readFileSync(skillpointPath, 'utf8');
                const data = JSON.parse(content);
                
                // 只更新第四区域，不清空其他区域
                const card4 = document.querySelector('.card-4');
                card4.innerHTML = '<div class="attribute-cards"></div>';
                const container = card4.querySelector('.attribute-cards');
                
                // 筛选指定类型的属性
                const filteredAttributes = data.attributes.filter(attr => attr.type === type);
                
                // 显示筛选后的属性
                filteredAttributes.forEach(attr => {
                    const card = document.createElement('div');
                    card.className = 'attribute-card';
                    
                    let title = '';
                    let content = '';
                    
                    switch(type) {
                        case 'ability':
                            title = `${attr.name}: ${attr.currentValue || 0}`;
                            if (isAbilityDetailMode) {
                                content = `
                                    <div class="method-detail">
                                        <div class="detail-section">
                                            <h4>详情</h4>
                                            <p>${attr.detail || '暂无详情'}</p>
                                        </div>
                                        ${attr.increase ? `
                                            <div class="detail-section">
                                                <h4>增长途径</h4>
                                                <p>${attr.increase}</p>
                                            </div>
                                        ` : ''}
                                        ${attr.decrease ? `
                                            <div class="detail-section">
                                                <h4>降低途径</h4>
                                                <p>${attr.decrease}</p>
                                            </div>
                                        ` : ''}
                                    </div>
                                `;
                            } else {
                                content = attr.detail || '暂无详情';
                            }
                            break;
                        case 'material':
                            title = `${attr.name}: ${attr.currentValue || 0}${attr.unit || ''}`;
                            if (isMaterialDetailMode) {
                                content = `
                                    <div class="method-detail">
                                        <div class="detail-section">
                                            <h4>详情</h4>
                                            <p>${attr.detail || '暂无详情'}</p>
                                        </div>
                                        ${attr.increase ? `
                                            <div class="detail-section">
                                                <h4>获取途径</h4>
                                                <p>${attr.increase}</p>
                                            </div>
                                        ` : ''}
                                        ${attr.decrease ? `
                                            <div class="detail-section">
                                                <h4>消耗途径</h4>
                                                <p>${attr.decrease}</p>
                                            </div>
                                        ` : ''}
                                    </div>
                                `;
                            } else {
                                content = attr.detail || '暂无详情';
                            }
                            break;
                        case 'method':
                            title = attr.name;
                            if (isMethodDetailMode) {
                                content = `
                                    <div class="method-detail">
                                        <div class="detail-section">
                                            <h4>详情</h4>
                                            <p>${attr.detail || '暂无详情'}</p>
                                        </div>
                                        ${attr.amplification && attr.amplification.length > 0 ? `
                                            <div class="detail-section">
                                                <h4>增幅途径</h4>
                                                <ul class="detail-list">
                                                    ${attr.amplification.map(item => `<li>${item}</li>`).join('')}
                                                </ul>
                                            </div>
                                        ` : ''}
                                        ${attr.notes && attr.notes.length > 0 ? `
                                            <div class="detail-section">
                                                <h4>注意事项</h4>
                                                <ul class="detail-list">
                                                    ${attr.notes.map(item => `<li>${item}</li>`).join('')}
                                                </ul>
                                            </div>
                                        ` : ''}
                                    </div>
                                `;
                            } else {
                                content = attr.detail || '暂无详情';
                            }
                            break;
                    }
                    
                    card.innerHTML = `
                        <div class="card-title">${title}</div>
                        <div class="card-content">${content}</div>
                    `;
                    
                    container.appendChild(card);
                });
            }
        }
    } catch (error) {
        console.error('Error filtering attributes:', error);
        document.querySelector('.card-4').innerHTML = '读取属性失败：' + error.message;
    }
}

// 添加增幅方式
window.addAmplification = function() {
    const list = document.getElementById('amplificationList');
    const itemId = `amp_${Date.now()}`;
    
    const itemHtml = `
        <div class="method-item" id="${itemId}">
            <input type="text" class="method-input" placeholder="输入增幅方式...">
            <button type="button" class="remove-btn" onclick="removeMethodItem('${itemId}')">×</button>
        </div>
    `;
    
    list.insertAdjacentHTML('beforeend', itemHtml);
};

// 添加注意事项
window.addCaution = function() {
    const list = document.getElementById('cautionList');
    const itemId = `caution_${Date.now()}`;
    
    const itemHtml = `
        <div class="method-item" id="${itemId}">
            <input type="text" class="method-input" placeholder="输入注意事项...">
            <button type="button" class="remove-btn" onclick="removeMethodItem('${itemId}')">×</button>
        </div>
    `;
    
    list.insertAdjacentHTML('beforeend', itemHtml);
};

// 移除列表项
window.removeMethodItem = function(itemId) {
    const item = document.getElementById(itemId);
    if (item) {
        item.remove();
    }
};

// 修改导出部分，添加新函数
module.exports = {
    displaySkillpointContent,
    showAttributeTypeSelection,
    showAttributeForm,
    showAttributeDetail,
    addListItem
}; 